package com.zhj.bz.algorithm.sort;

import com.zhj.tool.CallBack;
import com.zhj.tool.TimeTools;

import java.util.Arrays;

/**
 * @author zhj
 */
public class MergeSort {

    public static void main(String[] args) {
        int[] nums = {8, 4, 5, 7, 1, 3, 6, 2};
        mergeSort(nums, 0, nums.length-1, new int[nums.length]);
        System.out.println(Arrays.toString(nums));

        int[] bigArr = new int[10000000];
        for (int i = 0; i < 10000000; i++) {
            bigArr[i] = (int) (Math.random() * 80000);
        }
        System.out.println("归并排序：");
        TimeTools.useTime(new CallBack(){
            //定义execute方法
            public void execute(){
                mergeSort(bigArr, 0, bigArr.length-1, new int[bigArr.length]);
            }
        });
    }

    public static void mergeSort(int[] nums, int left , int right, int[] temp) {
        if (left >= right) {
            return;
        }
        int mid = left + (right - left)/2;
        mergeSort(nums, left, mid, temp);
        mergeSort(nums, mid + 1, right, temp);
        merge(nums, left, mid, right, temp);
    }

    /**
     *
     * @param nums
     * @param left 左边索引
     * @param mid 中间索引
     * @param right 右侧索引
     * @param temp 临时数组
     */
    public static void merge(int[] nums, int left, int mid, int right, int[] temp) {
        int i = left;
        int j = mid + 1;
        int tempCurIndex = 0;
        while (i <= mid && j <= right) {
            if (nums[i] <= nums[j]) {
                temp[tempCurIndex] = nums[i];
                tempCurIndex++;
                i++;
            } else {
                temp[tempCurIndex] = nums[j];
                tempCurIndex++;
                j++;
            }
        }

        while (i <= mid) {
            temp[tempCurIndex] = nums[i];
            tempCurIndex++;
            i++;
        }

        while (j <= right) {
            temp[tempCurIndex] = nums[j];
            tempCurIndex++;
            j++;
        }
        tempCurIndex = 0;
        int tempLeft = left;
        while (tempLeft <= right) {
            nums[tempLeft] = temp[tempCurIndex];
            tempCurIndex++;
            tempLeft++;
        }
    }
}
